package com.my.interview.jvm.study;

public class FinalizeEscapeGC {

    public static FinalizeEscapeGC SAVE_HOOK = null;

    public void isAlive(){
        System.out.println("yes, I am still alive :)");
    }

    //finalize 只被系统自动调用一次
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("Finalize method executed!!");
        FinalizeEscapeGC.SAVE_HOOK = this;
    }


    public static void main(String[] args) throws Throwable{

        SAVE_HOOK = new FinalizeEscapeGC();
        //对象第一次成功拯救自己
        SAVE_HOOK = null;
        System.gc();

        Thread.sleep(1000);
        if(SAVE_HOOK != null){
            SAVE_HOOK.isAlive();
        }else{
            System.out.println("No, I am dead :(");
        }

        //对象第二次拯救自己失败，因为finalize只能调用一次
        SAVE_HOOK = null;
        System.gc();

        Thread.sleep(1000);
        if(SAVE_HOOK != null){
            SAVE_HOOK.isAlive();
        }else{
            System.out.println("No, I am dead :(");
        }
    }
}
